namespace BaseProject.Infrastructure.Extensions
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Reflection;
    using System.Resources;

    public static class EnumExtensions
    {
        public static IEnumerable<T> ToArrayEnum<T>(this Type value)
        {
            return Enum
                    .GetValues(value)
                    .Cast<int>()
                    .Where(r => r != 0)
                    .Cast<T>()
                    .ToArray();
        }

        public static string ToStringInt(this Enum value)
        {
            return value.ToString("d");
        }

        public static string ToStringLower(this Enum value)
        {
            return value.ToString().ToLower();
        }

        public static string ToDescription(this Enum value)
        {
            var attributes = (DescriptionAttribute[])value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
            return attributes.Length > 0 ? attributes[0].Description : value.ToString();
        }

        public static string GetDisplayName(this Enum enumValue)
        {
            var displayAttrib = enumValue.GetType()
                        .GetMember(enumValue.ToString())
                        .First()
                        .GetCustomAttribute<DisplayAttribute>();
            var name = displayAttrib.Name;
            var resource = displayAttrib.ResourceType;

            return String.IsNullOrEmpty(name) ? enumValue.ToString()
                : resource == null ? name
                : new ResourceManager(resource).GetString(name);
        }
    }
}